<!--详情页面-->
<template>
  <h1>详情页</h1>
  <hr>
  <h1>{{weibo.nickname}} 说了: {{weibo.content}}</h1>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <el-input v-model="comment.content" placeholder="说点啥..." style="width:500px;"></el-input>
  <el-button type="primary" @click="post()" style="margin:10px;">发评论</el-button>
  <div v-for="c in arr">
    <h4>{{c.nickname}} 评论说: {{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

  const weibo = ref({});
  onMounted(()=>{
    //得到url中的id值
    let id = new URLSearchParams(location.search).get('id');
    //页面一打开就要加载评论,传入本条微博的id
    loadComments(id);
    //alert(id);
    //发请求获取指定id的本条微博的详情
    axios.get('http://localhost:8080/v1/weibos/'+id+'/detail')
    .then((response)=>{
      if(response.data.code==2001){
        weibo.value = response.data.data;
      }
    })
  })

  const comment = ref({content:''});
  const post = ()=>{
    let user = localStorage.user?JSON.parse(localStorage.user):null;
    if(user==null){
      ElMessage.error('请先登录！');
      router.push('/login');
      return;
    }
    comment.value.userId = user.id;//谁评论的
    comment.value.weiboId = weibo.value.id;//评论的是哪条微博
    let data = qs.stringify(comment.value);
    //console.log(data);
    axios.post('http://localhost:8080/v1/comments/add-new',data)
    .then((response)=>{
      if(response.data.code==2001){
        ElMessage.success('评论成功!');
        //评论成功后也要加载评论
        loadComments(weibo.value.id);
      }
    })
  }
  //定义数组保存所有请求回来的评论数据
  const arr = ref([]);
  //定义加载评论的函数,谁调用谁传参(本条微博的id)
  const loadComments = (id)=>{
    axios.get('http://localhost:8080/v1/comments/'+id)
    .then((response)=>{
      if(response.data.code==2001){
        //将请求回来的评论数据存入上方的arr数组中,arr与页面元素绑定显示评论列表
        arr.value = response.data.data;
      }
    })
  }
</script>

<style scoped>

</style>